<template>
  <div class="common-header">
    <el-dialog
      title=" "
      :visible.sync="user.isLoginDialogVisible"
      :close-on-click-modal="false" modal-append-to-body lock-scroll :close-on-press-escape="false"
      width="1000px"
      center>
      <div class="popbox">
        <div class="zuobox">
          <div class="titname">
            <!-- 手机扫码 -->
          </div>
          <div class="erweimabox">
            <img src="../../assets/images/header.png" alt="">
            <!-- <iframe style="width: 400px;height: 470px;" :src="qrcode" frameborder="0"></iframe>
            <div class="fucheng" v-if="zhuangtai=='scanned'||zhuangtai=='confirmed'||zhuangtai=='expired'">
               <i v-if="zhuangtai=='confirmed'" class="el-icon-check zhuantai1"></i>
               <i v-if="zhuangtai=='scanned'"  class="el-icon-close zhuantai2"></i>
               <i v-if="zhuangtai=='expired'" class="el-icon-refresh-left zhuantai3"></i>
            </div> -->
          </div>
        </div>
        <div class="line">

        </div>
        <div class="youbox">
          <div class="tabs">
            <div class="tab1 tab" :class="acit==1?'acit':'noac'" @click="tapit(1)">登录</div>
            <!-- <div class="tab2 tab" :class="acit==2?'acit':'noac'" @click="tapit(2)">注册</div> -->
          </div>
          <div class="inputbox inputbox1">
            <div class="guding">+86</div>
            <div class="icon">
              <i class="el-icon-user"></i>
            </div>
            <div class="inputs">
              <el-input v-model="form.customerPhone" placeholder="请输入手机号" type="number" maxlength="11" clearable></el-input>
            </div>
          </div>
          <div class="inputbox inputbox1">
            <div class="guding">密码 </div>
            <div class="icon">
              <i class="el-icon-lock"></i>
            </div>
            <div class="inputs">
              <el-input v-model="form.customerPassword" placeholder="请输入密码" :type="showPassword?'text':'password'" maxlength="30" clearable>
                <template slot="append">
                  <i class="el-icon-view" @click="showPassword = !showPassword"></i>
                </template>
              </el-input>
            </div>
          </div>
          <div class="inputbox inputbox1" v-show="acit==2">
            <div class="guding">确认密码 </div>
            <div class="icon">
              <i class="el-icon-lock"></i>
            </div>
            <div class="inputs">
              <el-input v-model="form.customerPassword2" placeholder="请输入密码" :type="showPassword2?'text':'password'" maxlength="30" clearable>
                <template slot="append">
                  <i class="el-icon-view" @click="showPassword2 = !showPassword2"></i>
                </template>
              </el-input>
            </div>
          </div>
          <!-- <div class="inputbox inputbox2">
            <div class="inputs">
              <el-input v-model="form.codeNum"  placeholder="请输入验证码" type="number" maxlength="6" clearable></el-input>
            </div>
            <div class="codeNumbtn">
              <el-button type="text" @click="dianjita" :disabled="dianle">{{times==60||times==0 ?'获取验证码':times+'秒后重发'}}</el-button>
            </div>
          </div> -->
          <div class="inputbox3" v-show="acit==2">
            <el-checkbox v-model="checked">
              已阅读并同意梯语云保险账号
             <span @click.stop="toProtocol(1)">用户协议</span> 
              和
              <span @click.stop="toProtocol(2)">隐私政策</span> 
            </el-checkbox>
          </div>
          <el-button class="btnconfirm" type="primary" @click="closeit">{{ acit==1?'登录':'注册' }}</el-button>
          
        </div>
      </div>
    </el-dialog>
  </div>
</template>
 
<script >
import { mapState, mapActions } from 'vuex';
import { login } from "@/api/login"
import QRCode from 'qrcodejs2'
export default {
  data() {
    return {
      dianle:false,
      times:60 ,
      timer:null,
      acit:1,//1登录2注册
      form:{
        customerPhone:'',//手机号
        codeNum:'',//验证码
      },
      checked:false,
      qrcode:'data:image/png;base64,',
      uuid:'',
      pollInterval:2000,
      pollCount:0,
      pollTimer:null,
      zhuangtai:'',
      showPassword:false,
      showPassword2:false
    }
  },
  computed: {
    ...mapState(['user']),
    
  },
  watch:{
    user:{
      handler(n,o){
        if(n){
          console.log(n)
          if(n.isLoginDialogVisible===true){
            // this.init()
            // setTimeout(() => {
            //   this.startPolling(this.uuid)
            // }, 1000);
          }else{
            clearInterval(this.pollTimer)
          }
          
        }else{
          clearInterval(this.pollTimer)
        }
      },
      deep:true
    }
  },
  created() {
    var times=localStorage.getItem("times")
    if(times){
      this.times=times
      this.getnumtimer()
    }
   
  },
  mounted() {
     
  },
  beforeDestroy() {
    if(this.timer&&this.times>0){
      localStorage.setItem("times",this.times)
      clearInterval(this.timer)
    }else{
      localStorage.removeItem("times")
      clearInterval(this.timer)
    }
    clearInterval(this.pollTimer)
    // document.getElementById('qrcode').innerHTML = "";

  },
  methods: {
    toProtocol(num){
      this.$router.push({
        path:'/protocol',
        query:{
          num:num
        }
      })
    },
    ...mapActions(['closeLoginDialog','changeCustomerId']),
    getBase64URL(pic) {
        const blob = base64ImgtoFile(pic)
        const blobUrl = window.URL.createObjectURL(blob);
        return blobUrl
    },
    async init(){
      this.qrcode='data:image/png;base64,'
      const res =await getQrcode()
      console.log(res)
      this.qrcode+=res.data.qrCodeBase64
      this.qrcode=res.data.qrCodeUrl
       this.uuid=res.data.qrCodeId
        // this.$nextTick(() => {
        //      this.qrcodeGenerate()
        //   })
    },
    qrcodeGenerate() {
          document.getElementById('qrcode').innerHTML = "";

      let qrcode = new QRCode('qrcode', {
          width: 200, // 设置宽度，单位像素
          height: 200, // 设置高度，单位像素
          correctLevel:QRCode.CorrectLevel.L, // 设置容错等级，H为最高
          text: this.qrcode // 设置二维码内容或跳转地址

      })
    },
    startPolling(uuid) { // 立即执行第一次检查 
       this.pollInterval=2000
      this.pollCount=0
      this.pollTimer=null
      this.checkLoginStatus(uuid); // 设置轮询定时器 
      this.pollTimer = setInterval(() => { 
        this.pollCount++; 
        this.checkLoginStatus(uuid); // 根据轮询次数动态调整间隔 
        if (this.pollCount >= 15 && this.pollInterval < 5000) { // 30秒后 
          this.pollInterval = 5000; // 改为5秒 
          clearInterval(this.pollTimer); 
          this.pollTimer = setInterval(() => this.checkLoginStatus(uuid), this.pollInterval); 
        } else if (this.pollCount >= 60) { // 120秒后 
          this.pollInterval = 10000; // 改为10秒 
          clearInterval(this.pollTimer); 
          this.pollTimer = setInterval(() => checkLoginStatus(uuid), this.pollInterval); 
        } 
      }, this.pollInterval); 
    },
    async checkLoginStatus(uuid) {
      const res =await checkQrcode({
        qrCodeId:uuid,
      }).catch(error => { console.error('轮询出错:', error)})
      console.log(data)
      var data=res.data
      switch(data) { 
        case '0': // 显示等待扫码状态 
        this.zhuangtai='0'
       
        break; 
        case '1': // 显示已扫码状态 
        this.zhuangtai='1'
        break; 
        case '2': // 登录成功，跳转页面 
        clearInterval(this.pollTimer); 
        this.zhuangtai='2'
        console.log('成功')
        break; 
        case '3': // 二维码过期，重新生成 
        clearInterval(this.pollTimer); 
        this.zhuangtai='3'
        setTimeout(() => {
          this.init(); 
          setTimeout(() => {
            // this.startPolling(this.uuid)
          }, 1000);
        }, 1000);
        
        break; 
      }  
    },
    tapit(num){
      this.acit=num
    },
    async closeit(){
      if(this.acit==1){
        if(!this.form.customerPhone){
          return this.$message.error("请输入手机号");
        }
        if(!this.form.customerPassword){
          return this.$message.error("请输入密码");
        }
        console.log("关闭它")
        const res =await login({
          userName:this.form.customerPhone,
          userPhone:this.form.customerPhone,
          userSource:1,//用户来源 
        })
        console.log(res)
        if(res.code !=200){
          return this.$message.error(res.msg);
        }
        if(res.data.openid){
          localStorage.setItem("openid",res.data.openid)
        }
        this.$message.success("登录成功");
        localStorage.setItem("customer",JSON.stringify(res.data))
        this.changeCustomerId(res.data)
        this.closeLoginDialog()
        this.$router.go(0)
      }else{
        if(!this.form.customerPhone){
          return this.$message.error("请输入手机号");
        }
        if(!this.form.customerPassword){
          return this.$message.error("请输入密码");
        }
        if(!this.form.customerPassword2){
          return this.$message.error("请再次输入密码");
        }
        if(!this.checked){
          return this.$message.error("请同意用户协议和隐私政策");
        }
      }
      
    },
    async dianjita(){
      if(this.dianle){
        return
      }
      if(!this.form.customerPhone){
        return this.$message.error("请输入手机号");
      }
     
      const res =await getcodeNum(this.form.customerPhone)
      console.log(res)
      if(res.code!=200){
        return this.$message.error(res.msg);
      }
      this.$message.success(res.msg)
      this.dianle=true
      this.times= 60 
      this.getnumtimer()
    },
    getnumtimer(){
      this.timer=setInterval(()=>{
        if(this.times<=0){
          localStorage.removeItem("times")
          this.dianle=false
          clearInterval(this.timer)
          return
        }
        this.times--
      },1000)
    },
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-input-group__append{
  border: none !important;
}
::v-deep input::-webkit-outer-spin-button,
::v-deep input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
::v-deep input[type='number'] {
  -moz-appearance: textfield !important;
  }

::v-deep .el-dialog{
  border-radius: 16px;
}
.popbox {
  width: 100%;
  height: 492px;
  display: flex;
  align-items: center;
  justify-content: center;
  ::v-deep .el-input__inner{
    border: none;
    background: #F7F8FC;
  }
  .zuobox{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .titname{
      font-weight: bold;
      font-size: 24px;
      color: #333333;
      text-align: center;
      margin-bottom: 10px;
    }
    .erweimabox{
      width: 400px;
      height: 480px;
      display: flex;
      align-items: center;
      justify-content: center;
      // border: 1px solid #EBEBEB;
      border-radius: 6px;
      overflow: hidden;
      img{
        width: 384px;
        height: 176px;
      }
    }
  }
  .line{
    width: 1px;
    height: 332px;
    background: #EBEBEB;
    border-radius: 0px 0px 0px 0px;
    margin: auto 40px auto 45px;
  }
  .youbox{
    height: 450px;
    position: relative;
    .tabs{
      display: flex;
      align-items: center;
      margin-bottom: 40px;
      .tab{
        font-weight: bold;
        font-size: 24px;
      }
      .tab1{
        margin-right: 80px;
      }
      .acit{
        color: #0672F9;
      }
      .noac{
        color: #333333;
      }
    }
    .inputbox{
      width: 400px;
      height: 56px;
      background: #F7F8FC;
      border-radius: 8px 8px 8px 8px;
      display: flex;
      align-items: center;
      padding: 0 16px;
      box-sizing: border-box;
      .inputs{
        flex: 1;
        
      }
    }
    .inputbox1{
      font-weight: 400;
      font-size: 16px;
      color: #4F4F4F;
      text-align: left;
      margin-bottom: 16px;
      .guding{
        margin-right: 4px;
      }
      .icon{
        margin-right: 16px;
      }
     
    }
    .inputbox2{
      margin-bottom: 64px;
      .codeNumbtn{
        margin-left: 16px;
      }
    }
    .inputbox3{
      position: absolute;
      bottom: 80px;
      left: 0;
      font-weight: 400;
      font-size: 12px;
      color: #BDBDBD;
      text-align: left;
      span{
        color:#4F4F4F;
      }
    }
    .btnconfirm{
      width: 400px;
      height: 56px;
      background: #0672F9;
      border-radius: 8px 8px 8px 8px;
    }
    .btnconfirm:hover{
      opacity: 0.5;
    }
  }

}
</style>
